<template>
  <div class="form-layout">
    <!--左侧导航-->
    <div class="nav-left">
      <customAnchor
        :itemList="[
          { name: 'box-base', title: '合单信息' },
          { name: 'box-dtl', title: '合单明细' },
        ]"
      />
    </div>

    <!--表单区域-->
    <div class="form-right" ref="formRight">
      <div id="box-base" class="box-title">合单信息</div>
      <customForm :data="form" :rules="propRules" ref="editForm" :disabled="propReadonly">
        <template #content>
          <customFormItem label="合单类型" name="mergeType" :parent="_self" :form="form"
                          :type="constCommon.formItemType.selectDict.name"
                          :config="{dictType: constCommon.dictType.mergeType}"
                          :disabled="!propParent.cpFormNew"
                          help="保存后不可修改，将根据合单类型选择不同的数据"
          />
          <customFormItem label="合单日期" name="busDate" :parent="_self" :form="form"
                          :type="constCommon.formItemType.datePicker.name"
                          :disabled="!propParent.cpFormNew"
                          help="保存后不可修改"
          />

          <customFormItem
            label="合单科室" name="deptName" :parent="_self" :form="form"
            :readonly="true" :showSelectIcon="true"
            @focus="utilSelect.dept(deptChange)"
            :disabled="!propParent.cpFormNew"
            help="保存后不可修改"
          />

          <customFormItem label="按科室合单" name="flagLine" :parent="_self" :form="form"  :type="constCommon.formItemType.switch.name"
                  :disabled="!propParent.cpFormNew"
                  help="保存后不可修改，如果是，则将根据筛选合单科室相关的业务数据"
          />
          <customFormItem label="操作类型" name="busType" :parent="_self" :form="form"
                          :type="constCommon.formItemType.selectDict.name"
                          :config="{dictType: constCommon.dictType.deptUseMerge}"
                          disabled
          />
          <customFormItem label="单据标识" name="busKey" :parent="_self" :form="form" disabled  />
          <customFormItem label="合单人" name="busUser" :parent="_self" :form="form" disabled  />
          <customFormItem v-show="cpMergeType1"  label="住院号" name="inpatientNo" :parent="_self" :form="form"
                          :readonly="true" :showSelectIcon="true"
                          @focus="$refs.tableDrawerOprtUseSelect.show()"
                          :disabled="!propParent.cpFormNew"
                          help="保存后不可修改"
          />
          <customFormItem v-show="cpMergeType1"  label="门诊号" name="outpatientNo" :parent="_self" :form="form"
                          :readonly="true" :showSelectIcon="true"
                          @focus="$refs.tableDrawerOprtUseSelect.show()"
                          :disabled="!propParent.cpFormNew"
                          help="保存后不可修改"
          />
          <customFormItem v-show="cpMergeType1"  label="病人" name="patientName" :parent="_self" :form="form" disabled/>
          <customFormItem label="金额" name="amount" :parent="_self" :form="form" disabled  />

          <customFormItem label="备注" name="remark"  :parent="_self" :form="form" />
        </template>
      </customForm>

      <div id="box-dtl" class="box-title">合单明细</div>
      <data-view
                 propViewKey="dept_use_merge_dtl"
                 ref="childDataView"
                 :propAutoFetchData="false"
                 :propNoEditRow="true"
                 @extra-button-click="extraButtonClick"
                 :propFilterBtn="propFilterBtn"
                 :propTableHide="propParent.cpFormNew"
                 propTableHideMsg="请先保存主单据再操作"

                 :propFlowKey="propParent.propFlowKey"
                 :propInitData="form"
                 :propParentPage="_self"
                 :propHideFlowSelect = "true"
                 :propParentData="propParent.viewFormData"
      />
    </div>

    <!--病人消耗单选择-->
    <tableDrawer loadForce ref="tableDrawerOprtUseSelect" refName="tableDrawerOprtUseSelect" @confirm="selectChange" viewKey="merge_oprt_use_select"/>

    <!--科室消耗单选择-->
    <tableDrawer loadForce ref="tableDrawerUseSelect" refName="tableDrawerUseSelect" viewKey="merge_dept_use_select"
                 showCheckbox
                 :showRadiobox="false"
                 :subtitle="form.flagLine ? '数据筛选: 当前所选合单科室' : '数据筛选: 所有可合单数据'"
                 :queryWrapper="cpQueryWrapper"
    />
  </div>
</template>

<script>
import customAnchor from '@/components/custom/form/customAnchor.vue'

export default {
  data() {
    return {
      form: {},
    }
  },
  methods: {
    // 列表查询条件
    getChildViewQueryWrapper() {
      if (this.form.id) {
        return this.$newWrapper().eq('use_merge_id', this.form.id)
      } else {
        return this.$newWrapper().ne(1, 1)
      }
    },
    async extraButtonClick({ button, data, index }) {
      let buttonKey = button.key
      if (buttonKey === 'mergeBtn') { // 科室消耗单，手动合单
        this.$refs.tableDrawerUseSelect.show(this.confirmCheck, true)
      } else if (buttonKey === 'autoMergeBtn') {// 病人消耗单，自动合单
        this.handleOpenAutoMerge()
      }
    },

    // 科室消耗单选择后
    confirmCheck(rows) {
      let that = this
      rows.forEach(o => {
        o.mergeId = this.form.id
      })
      this.$ajax.post('/dept/use_merge/saveByUseIds', rows).then((resp) => {
        this.utilMessage.success('保存数据成功！')
        this.$refs.childDataView.fetchData()
        that.$refs.childDataView.propParentPage.$emit('refresh-row')
      })
    },

    // 自动合单
    handleOpenAutoMerge() {
      let that = this
      let text = ''
      let url = ''
      if (!this.cpMergeType1) {
        text = '当天同科室的单据合单'
        url = `/dept/use_merge_dtl/autoMerge?useMergeId=${this.form.id}`
      } else {
        text = '消耗科室、日期、门诊号或住院号进行合单'
        url = `/dept/use_merge/autoMergeOprtUseMain?useMergeId=${this.form.id}`
      }
      this.$confirm('将按照' + text + ',是否确认?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        this.utilVue.loadShow(true)
        this.$ajax.post(url).then((resp) => {
          if (resp.code == 0) {
            this.utilMessage.success(resp.msg)
            this.$refs.childDataView.fetchData()
            that.$refs.childDataView.propParentPage.$emit('refresh-row')
          }
          this.utilVue.loadHide()
        })
      }).catch(() => {
      })
    },

    // 病人消耗单选择后
    selectChange(row, refName) {
      this.$set(this.form, 'inpatientNo', row.inpatientNo)
      this.$set(this.form, 'outpatientNo', row.outpatientNo)
      this.$set(this.form, 'patientId', row.patientId)
      this.$set(this.form, 'deptId', row.deptId)
      this.$set(this.form, 'deptName', row.deptName)
      this.$set(this.form, 'patientName', row.patientName)
      this.$set(this.form, 'patientNo', row.patientNo)
    },


    // 过滤显示按钮
    propFilterBtn(btnList) {
      if (this.propReadonly) {
        return btnList.filter(btn => !['mergeBtn', 'autoMergeBtn'].includes(btn.code))
      }
      // 病人消耗合单
      if (this.cpMergeType1) {
        return btnList.filter(btn => !['mergeBtn'].includes(btn.code))
      } else {
        return btnList.filter(btn => !['autoMergeBtn'].includes(btn.code))
      }
      return btnList
    },
    // 选择科室
    deptChange(row) {
      this.$set(this.form, 'deptId', row.id)
      this.$set(this.form, 'deptName', row.name)
    }
  },
  created() {
    let that = this
    this.$emit('event-register', {
      validate: (callback) => {
        return this.$refs.editForm.validate(callback)
      },
      beforeSave: () => {
        if (this.cpMergeType1) {
          // 病人消耗合单
          if (this.strings.isBlank(this.form.inpatientNo)) {
            this.utilMessage.warning('住院号不能为空')
            return false
          }
        }
        this.$emit('data-callback', this.form)
        return true
      },
      afterMove: (formData, initData) => {
        this.form = global.utils.jsonClone(formData)

        // 新增，设置默认值
        if (!this.form.id) {
          this.$set(this.form, 'busDate', new Date().format('yyyy-MM-dd'))
          this.$set(this.form, 'warehouseId', this.utils.getCurrentWarehouse().id)
          this.$set(this.form, 'warehouseName', this.utils.getCurrentWarehouse().name)
          this.$set(this.form, 'deptId', this.utils.getCurrentUser().deptId)
          this.$set(this.form, 'deptName', this.utils.getCurrentUser().deptName)
          this.$set(this.form, 'busType', 'manual')
          this.$set(this.form, 'busUser', this.utils.getCurrentUser().name)
          this.$set(this.form, 'flagLine', false)
          this.$set(this.form, 'mergeType', '2')
          // 保存主表
          // this.$emit('save', this.form)
        }
        let wrapper = this.getChildViewQueryWrapper()
        this.$refs.childDataView && this.$refs.childDataView.setQueryWrapper(wrapper)
      },
      dataRefresh: (formData) => {
        this.form = global.utils.jsonClone(formData)
      },
      afterSave: () => {
      },
      beforeDelete: () => {
        return true
      },
      afterDelete: () => {
      },
      beforeFlow: (flowButtonKey) => {
        if (flowButtonKey == 'submit') {
          if (this.$refs.childDataView.getRows().length == 0) {
            this.utilMessage.warning('消耗合单明细为空，不能提交')
            return false
          }
        }
        return true
      },
      afterFlow: (flowButtonKey) => {
      },
      beforeClose: () => {
        return true
      },
      async afterClick(button, data, viewForm) {
        let {key: buttonKey} = button
        if (buttonKey == 'print') { //打印汇总
          let param = {
            'that': that, //当前调用对象
            configList: [ //打印配置，可以多个
              {
                //打印配置
                printBusType: 'deptUseMergeCollect', //打印业务类型，来源print_template.bus_type，同constPrint.busKey
                //主单据数据或者数据查询配置
                formData: that.form, //数据对象
                formDataId: that.form.id,
              }
            ]
          }
          global.utilPrint.openFormPrint(param)
        }else if (buttonKey == 'printdtl') { //打印明细
          let param = {
            'that': that, //当前调用对象
            configList: [ //打印配置，可以多个
              {
                //打印配置
                printBusType: 'deptUseDetailMerge', //打印业务类型，来源print_template.bus_type，同constPrint.busKey
                //主单据数据或者数据查询配置
                formData: that.form, //数据对象
                formDataId: that.form.id,
              }
            ]
          }
          global.utilPrint.openFormPrint(param)
        }
      }
    })
  },
  props: {
    propParent: Object,
    propInitData: Object,
    propPrimaryKey: String,
    propDictionaries: Object,
    propCurrentRow: Object,
    propViewFormData: Object,
    propReadonly: Boolean,
    propStatus: String,
    propRules: Object,
    propParentPage: Object,
  },
  components: {
    customAnchor
  },
  computed: {

    // 是否是病人消耗合单
    cpMergeType1() {
      return this.form.mergeType == '1'
    },

    // 科室消耗查询条件
    cpQueryWrapper() {
      if (!this.form.flagLine) {
        return null
      }
      let wrapper = global.$newWrapper()
      wrapper.eq('deptId', this.form.deptId)
      return wrapper
    }
  },
  watch: {

  }
}
</script>

<style lang="scss" scoped>
</style>
